package com.reggie.controller;

import com.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传与下载
 * @program: reggie
 * @author:
 * @create: 2022-09-28 09:30
 **/
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.fileLocation}")
    private String fileLocation;
    /**
     * 文件的下载
     * */
    @GetMapping("/download")
    public R<String> download(String name, HttpServletResponse response){
        FileInputStream inputStream=null;
        ServletOutputStream outputStream = null;
        try {
            // 获得待下载文件所在文件夹的绝对路径
            String realPath = ResourceUtils.getURL("classpath:").getPath() + fileLocation;
            // 获得文件输入流
            inputStream = new FileInputStream(new File(realPath, name));
            // 设置响应头、以附件形式打开文件
            response.setHeader("content-disposition", "attachment; fileName=" + name);

            outputStream = response.getOutputStream();
            int len = 0;
            byte[] data = new byte[1024];
            while ((len = inputStream.read(data)) != -1) {
                outputStream.write(data, 0, len);
            }
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success("下载成功");
    }
    /**
     * 文件的上传
     * file是一个临时的文件，需要进行下载，否则会自行删除，所以提供下载功能
     *
     * MultipartFile 变量名要与 form 表单中的的 type="file" name="file"
     * name 属性名一致
     * */
    @PostMapping("/upload")
    public R<String> upload(HttpServletRequest request, MultipartFile file){
        //获取上传的文件的名称
        String filename = file.getOriginalFilename();
        log.info("文件的名称"+filename);

        //获取文件的后缀名
        /*获取文件的类型image/jpeg
        String contentType = file.getContentType();*/

        /*文件的后缀.jpg*/
        String suffix = filename.substring(filename.lastIndexOf("."));
        System.out.println("文件的后缀"+suffix);

        //利用UUID生成唯一的名称,防止名称的覆盖
        String name=UUID.randomUUID().toString().replace("-","")+suffix;

        String filePath= null;
        try {
            /*D:\Demo\JavaDemo\reggie\target\classes\static\files*/
            filePath = ResourceUtils.getURL("classpath:").getPath() +fileLocation;
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        //创建文件夹的类
        File dir = new File(filePath);

        log.info(dir.getPath());
        //如果文件夹不存在则创建
        if (!dir.exists()){
            dir.mkdir();
        }
        //将文件上传到文件夹中
        try {
            file.transferTo(new File(filePath+name));
        } catch (IOException e) {


        }
        return R.success(name);
    }
}
